package net.pulseproject.router.modules.logic;

import java.util.Timer;
import java.util.TimerTask;

import javax.sound.midi.ShortMessage;

import net.pulseproject.commons.misc.TimerTaskWrapper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@Deprecated
public class SustainedFireSuppresser implements SimpleListener, Runnable {

	private static final Log LOG = LogFactory.getLog(SustainedFireSuppresser.class);
	
	private final SimpleListener listener;
	
	private final long timeWindowInMs;
	
	private Timer timer;
	
	private ShortMessage storedMessage;
	
	
	public SustainedFireSuppresser(final SimpleListener listener, final long timeWindowInMs) {
		this.listener = listener;
		this.timeWindowInMs = timeWindowInMs;
	}
	
	@Override
	public final void onSimpleListened(final ShortMessage message) {
		if(this.timer != null) {
			LOG.trace("onSimpleListened(message) ... dropping message as it is within time window.");
			return;
		}
		
		LOG.trace("onSimpleListened(message) ... starting task timer.");
		
		this.storedMessage = message;
		final TimerTask task = new TimerTaskWrapper(this);
		this.timer = new Timer("SustainedFireSuppresserTimer");
		this.timer.schedule(task, this.timeWindowInMs);
	}

	@Override
	public final void run() {
		LOG.trace("run() ... dispatching stored message.");
		this.listener.onSimpleListened(this.storedMessage);
		this.timer = null;
		this.storedMessage = null;
	}
	
}
